﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    init();//调用初始化函数
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onConnected()
{
    ui->textRec->appendPlainText("已连接服务器"+m_tcpSocket->peerAddress().toString()+":"+QString::number(m_tcpSocket->peerPort()));
    ui->editAddress->setEnabled(false);
    ui->spinPort->setEnabled(false);
    ui->btnConnect->setText("已连接");
}

void MainWindow::onDisconnected()
{

}

void MainWindow::onReadRead()
{

    //根据传输模式处理套接字数据
    if(m_type == tpType::FILELIST){
        for(;m_tcpSocket->canReadLine();){

            QByteArray rec = m_tcpSocket->readLine();
            if(rec.startsWith("*#sendfilename#*")){
                rec.remove(0,16);
                rec.remove(rec.count() - 2,2);
                ui->listWidget->addItem(rec);
                ui->listWidget->item(ui->listWidget->count()-1)->setToolTip("file");
                ui->listWidget->item(ui->listWidget->count()-1)->setIcon(QIcon(":/imgs/file.png"));

            }else if(rec.startsWith("*#senddirname#*")){
                rec.remove(0,15);
                rec.remove(rec.count() - 2,2);
                ui->listWidget->addItem(rec);
                ui->listWidget->item(ui->listWidget->count()-1)->setToolTip("dir");
                ui->listWidget->item(ui->listWidget->count()-1)->setIcon(QIcon(":/imgs/dir.png"));

            }else if(rec.startsWith("*#dirpath#*")){
                rec.remove(0,11);
                rec.remove(rec.count() - 2,2);
                m_dirPath = rec;
            }
        }
    }else if(m_type == tpType::FILE){
        for(;m_tcpSocket->canReadLine();){
            m_file.write(m_tcpSocket->readAll());
            m_timer.stop();
            m_timer.start(3000);
        }
    }

}

void MainWindow::onTimerOut()
{

    //处理计时器超时事件
    m_timer.stop();
    m_type = tpType::FILELIST;
    ui->textRec->appendPlainText("文件接收完成.");
    m_file.close();

}

void MainWindow::init()
{

    //初始化参数
    m_tcpSocket = new QTcpSocket(this);

    m_type = tpType::FILELIST;

    ui->editSavePath->setText(QCoreApplication::applicationDirPath());

    //关联相关信号槽
    connect(m_tcpSocket,SIGNAL(connected()),this,SLOT(onConnected()));
    connect(m_tcpSocket,SIGNAL(disconnected()),this,SLOT(onDisconnected()));
    connect(m_tcpSocket,SIGNAL(readyRead()),this,SLOT(onReadRead()));
    connect(&m_timer,SIGNAL(timeout()),this,SLOT(onTimerOut()));
}


void MainWindow::on_btnConnect_clicked()
{
    if(!m_tcpSocket->isOpen()){

        m_tcpSocket->connectToHost(ui->editAddress->text(),ui->spinPort->value());
    }else{
        m_tcpSocket->disconnectFromHost();
        m_tcpSocket->close();

        ui->textRec->appendPlainText("已断开服务器连接.");
        ui->editAddress->setEnabled(true);
        ui->spinPort->setEnabled(true);
        ui->btnConnect->setText("已断开");
    }
}


void MainWindow::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{

    //处理文件列表双击事件
    if(item->toolTip() == "dir"){

        QString text = item->text();
        if(text == "."){
            return;
        }else if(text == ".."){
            ui->listWidget->clear();
            m_dirPath.remove(m_dirPath.lastIndexOf("/"),m_dirPath.count() - m_dirPath.lastIndexOf("/"));
            QString str = "*#getfilelist#*"+m_dirPath+"\r\n";

            m_tcpSocket->write(str.toUtf8());
        }else{
            ui->listWidget->clear();
            m_dirPath.append("/");
            m_dirPath.append(text);

            QString str = "*#getfilelist#*"+m_dirPath+"\r\n";

            m_tcpSocket->write(str.toUtf8());

        }
    }
}


void MainWindow::on_pushButton_2_clicked()
{

    //下载文件
    if(ui->listWidget->currentIndex().isValid() &&  ui->listWidget->currentItem()->toolTip() == "file"){
        QString filePath = m_dirPath+"/"+ui->listWidget->currentItem()->text();
        QString str = "*#getfile#*"+filePath+"\r\n";
        m_tcpSocket->write(str.toUtf8());
        m_type = tpType::FILE;

        QString fileName = ui->editSavePath->text()+"/"+ui->listWidget->currentItem()->text();
        m_file.setFileName(fileName);
        m_file.open(QIODevice::WriteOnly);
        ui->textRec->appendPlainText("正在接收文件:"+fileName);
        m_timer.start(3000);
    }
}


void MainWindow::on_btnBrowser_clicked()
{
    QString dirPath = QFileDialog::getExistingDirectory(0,"选择文件夹",QCoreApplication::applicationDirPath());
    QDir dir(dirPath);
    if(dir.exists()){
        ui->editSavePath->setText(dirPath);
    }
}

